package com.lap.auth.adapter.driving.persistence.role.repository;

import com.lap.auth.adapter.driving.persistence.role.RoleCache;
import com.lap.auth.adapter.driving.persistence.role.mapper.RoleMenuMapper;
import com.lap.auth.adapter.driving.persistence.role.po.RoleMenuPo;
import com.lap.auth.domain.role.repository.RoleMenuRepository;
import java.util.List;
import java.util.Set;
import lombok.RequiredArgsConstructor;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Repository;

@RequiredArgsConstructor
@Repository
public class RoleMenuRepositoryImpl implements RoleMenuRepository {

  private final RoleMenuMapper roleMenuMapper;

  @CacheEvict(value = RoleCache.ROLE_MENU, key = "#roleId")
  @Override
  public void saveAll(Integer roleId, Set<Integer> menuIds) {
    List<RoleMenuPo> list = menuIds.stream().map(menuId -> new RoleMenuPo(roleId, menuId)).toList();
    roleMenuMapper.insertBatch(list);
  }

  @CacheEvict(value = RoleCache.ROLE_MENU, key = "#roleId")
  @Override
  public void deleteByRoleId(Integer roleId) {
    roleMenuMapper.deleteByRoleId(roleId);
  }

  @Cacheable(value = RoleCache.ROLE_MENU, key = "#roleId", unless = "#result == null")
  @Override
  public List<Integer> findByRoleId(Integer roleId) {
    return roleMenuMapper.selectByRoleId(roleId);
  }
}
